import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useState, ChangeEvent, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Logins } from '../../../api/User'
import { Footer } from "antd/es/layout/layout"
//定义数据类型
type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

function Login() {
  const [username, setUsername] = useState<string>('')
  const [password, setPassword] = useState<string>('')
  const [remember, setRemember] = useState(true)
  const navigate = useNavigate()
  const backImg = `https://img.zcool.cn/community/01255258f41ec8a8012049ef106d6e.jpg@2o.jpg`
  const NameChange = (event: ChangeEvent) => {
    setUsername((event.target as HTMLInputElement).value)
  }
  const PasswordChange = (event: ChangeEvent) => {
    setPassword((event.target as HTMLInputElement).value)
  }
  const RememberChange = (event: ChangeEvent) => {
    setRemember(event.target.checked)
  }

  //这个函数会在表单提交成功时被调用
  const onFinish: FormProps<FieldType>['onFinish'] = async () => {
    Logins(username, password).then(res => {
      if (res.data.code == 200) {
        message.success('登录成功！')
        console.log(res)
        sessionStorage.setItem('role', res.data.data.user.userRole)
        //判断是否记住密码，若记住密码，将token存在本地
        console.log(res.data.data.token);
        if (remember == true) {
          localStorage.setItem('token', res.data.data.token)
        } else {
          sessionStorage.setItem('token', res.data.data.token)
        }
        navigate('/WorkSpace/GoodsList')
      }
      else {
        message.error(res.data.message)
      }
    })
  }


  //这个函数会在表单提交失败时被调用
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    message.error(errorInfo.errorFields[0].errors[0])
  }

  return (
    <div style={{
      position: "fixed",
      width: "100%",
      height: "100%",
      backgroundImage: `url(${backImg})`,
    }} >
      <div style={{
        width: "400px",
        margin: '15vh auto',
        textAlign: 'center',
        backgroundColor: "rgb(255,255,255)",
        border: "solid  rgb(231,232,234) 3px",
        borderRadius: '15px'
      }}>
        <h1 style={{
          fontWeight: "normal"
        }}>数 字 马 力</h1>
        <h4 style={{ fontWeight: "normal" }}>第 三 组 的  登 录 页 面</h4>
        {/*定义表单组件*/}
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 12 }}
          style={{ maxWidth: 400, }}
          initialValues={{ remember }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          validateTrigger="onBlur"
        >
          {/* 用户名 */}
          <Form.Item
            label="用户名："
            name="username"
            rules={[
              {
                required: true,
                message: '请输入你的用户名!'
              },
              {
                pattern: /^.{6,12}$/,
                message: '用户名在6-12个字符之间'
              }
            ]}
            initialValue={username}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="userName"
              onChange={NameChange} />
          </Form.Item>

          {/* 密码 */}
          <Form.Item<FieldType>
            label="密码："
            name="password"
            rules={[
              {
                required: true,
                message: '请输入你的密码!'
              },
              {
                pattern: /^.{6,20}$/,
                message: '密码在6-20位之间'
              },
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
                message: '密码需同时包含数字和字母'
              }
            ]}
            initialValue={password}
          >
            <Input.Password
              placeholder="password"
              prefix={<LockOutlined />}
              onChange={PasswordChange}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
            <Form.Item name="remember" valuePropName='checked' noStyle >
              <Checkbox onChange={RememberChange}>自动登录</Checkbox>
            </Form.Item>
            <a className="login-form-forgot" onClick={() => { navigate('/ResetPassword') }} style={{ marginRight: "15px", marginLeft: "15px" }} >
              忘记密码
            </a>|
            <a className="register" onClick={() => { navigate('/Register') }} style={{ marginLeft: "15px" }} >
              立即注册
            </a>
          </Form.Item>

          {/* 密码 */}
          <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
            <Button type="primary" htmlType="submit" >
              登录
            </Button>
          </Form.Item>


        </Form>
      </div>
      <Footer style={{ textAlign: 'center', backgroundColor: 'transparent' }}>
        Ant Design ©{new Date().getFullYear()} Created by Ant UED
      </Footer>
    </div>
  )
}

export default Login
